package com.ghsc.ghxc.jsb.ui.live.fragment

import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.cn.appcore.widget.RefreshHelper.Companion.onFinish
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.FragmentVideoViewpagerBinding
import com.ghsc.ghxc.jsb.ui.live.TabLiveVideoViewModel
import com.ghsc.ghxc.jsb.ui.live.adapter.VideoPlayPagerAdapter
import com.ghsc.ghxc.jsb.ui.live.bean.VideoDataBean
import com.ghsc.ghxc.jsb.ui.live.view.video.MultiStateView
import com.ghsc.ghxc.jsb.ui.live.view.video.viewHolder.VideoPlayPagerHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.cache.CacheFactory
import com.shuyu.gsyvideoplayer.cache.ProxyCacheManager
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.live.fragment
 * 类名：GHVideoListFragment
 * 创建时间：2024/5/10 11:02
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 自己的视频
 */
class GHVideoListFragment  : BaseVMFragment<TabLiveVideoViewModel, FragmentVideoViewpagerBinding>(
    R.layout.fragment_video_viewpager) {

    private val mPlayerTag = "GHVideoListFragment"
    val CUST_SIGN_SIFT_TAB = 222222
    var index: Int = 0

    companion object {
        fun getInstance(index: Int): GHVideoListFragment? {
            var fragment = GHVideoListFragment()
            fragment.index = index
            return fragment
        }
    }

    override fun attachVMClass(): Class<TabLiveVideoViewModel>? {
        return TabLiveVideoViewModel::class.java
    }

    override fun lazyLoad() {
        refreshData()
    }


    //    //应该是是否有下一页
    var isHasNext: Boolean = false

    //当前第几页
    var pagerNum: Int = 1

    //位置
    var positionIndex: Int = 0
    val mAdapter: VideoPlayPagerAdapter by lazy {
        VideoPlayPagerAdapter(
            requireActivity(),
            mPlayerTag
        )
    }
    var mList = arrayListOf<VideoDataBean>()

    var isRefreshData = false //是否下啦刷新


    private var mArticleCode = ""//每条数据的id


    override fun initView(savedInstanceState: Bundle?) {


        binding.refreshLayout.setEnableLoadMore(false)
        //adapter
        binding.vpVideoListPlay.orientation = ViewPager2.ORIENTATION_VERTICAL
        binding.vpVideoListPlay.adapter = mAdapter
        onSuccessList(mList, isHasNext)
        initPlayer()
        initRefreshLayout()
        mAdapter.setOnItemChildClickListener { view, position ->
            val itemData =
                mAdapter.getItemOrNull(position) ?: return@setOnItemChildClickListener
            mArticleCode = itemData.vid ?: ""
            when (view?.id) {
                R.id.btn_add_video_user -> {
                    //关注
                    showToast("暂未开放")
//                    val map: HashMap<String, Any> = HashMap()
//                    map["tuid"] = itemData.uid.toString()
//                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onUserFollowMethod(it1) }
                }

                R.id.iv_video_user_head -> {
                    //查看用户
                    showToast("暂未开放")
//                    var bundle =Bundle()
//                    bundle.putString("userid",itemData.uid)
//                    startActivity(HeMainActivity().javaClass,bundle)

                }

                R.id.btn_video_praise -> {
                    //点赞
                    showToast("暂未开放")
//                    val map: HashMap<String, Any> = HashMap()
//                    map["vid"] = itemData.vid.toString()
//                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onVideoLikeMethod(it1) }
                }

                R.id.btn_video_comment -> {
                    //评论
//                    showMsg("评论"+itemData.nickname)
                    showToast("暂未开放")
                }

                R.id.btn_video_collect -> {
                    //收藏
                    showToast("暂未开放")
//                    val map: HashMap<String, Any> = HashMap()
//                    map["vid"] = itemData.vid.toString()
//                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onVideoCollectMethod(it1) }
                }

                R.id.btn_video_share -> {
                    //分享
                    showToast("暂未开放")
                }
            }
        }

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CUST_SIGN_SIFT_TAB && rxBusBean.sign == CUST_SIGN_SIFT_TAB -> {
                        var index: Int = rxBusBean.anyBean as Int
                        if (index == 2) {
                            binding.vpVideoListPlay.postDelayed({
                                getShowPageHolder(positionIndex)?.startPlayer()
                            }, 50)
                        } else {
                            binding.vpVideoListPlay.postDelayed({
                                getShowPageHolder(positionIndex)?.pausePlayer()
                            }, 50)
                        }
                    }


                }
            }
    }


    /**
     * 根据位置 position 进行播放
     * 延迟
     */
    private fun playPosition(position: Int) {
        binding.vpVideoListPlay.postDelayed({
            getShowPageHolder(position)?.startPlayer()
        }, 50)

    }

    /**
     * 单个video的item
     */
    private fun getShowPageHolder(position: Int): VideoPlayPagerHolder? {
        val rvView = (binding.vpVideoListPlay.getChildAt(0) as? RecyclerView)
        val viewHolder = rvView?.findViewHolderForAdapterPosition(position)
        return viewHolder as? VideoPlayPagerHolder
    }


    /**
     * 刷新adapter数据
     */
    private fun onSuccessList(list: MutableList<VideoDataBean>?, hasNext: Boolean) {
        isHasNext = hasNext
        if (isRefreshData) {
            //如果是true 说明是下啦刷新
            isRefreshData = false
            GSYVideoManager.releaseAllVideos()
            mAdapter.setNewInstance(list)
            playPosition(positionIndex)
        } else {
            mAdapter.addData(list)
        }
        //延迟刷新
        binding.refreshLayout.postDelayed({
            //是否启动上啦加载更多
            binding.refreshLayout.setEnableLoadMore(!hasNext)
            binding.refreshLayout.onFinish(true, !hasNext)
            binding.msvVideoListPlay.viewState = if ((mAdapter.itemCount ?: 0) > 0) {
                MultiStateView.ViewState.CONTENT
            } else {
                MultiStateView.ViewState.EMPTY
            }
        }, 50)
    }


    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                refreshData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                loadMoreData()
            }
        })
    }

    /** 下啦刷新 **/
    fun refreshData() {
        pageNo = 1
        loadData(true, pageNo)
    }

    /** 加载更多 **/
    fun loadMoreData() {
        //如果没有下一页。return
        if (!isHasNext) {
            return
        }
        pageNo++
        loadData(false, pageNo)
    }

    /**
     * 下啦刷新请求的接口
     */
    fun loadData(isRefresh: Boolean, pageNo: Int) {
        isRefreshData = isRefresh
        //true 说明是下啦刷新了
        //发现
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = 10
        loge("视频分页=" + map.toString())
        GsonUtil.mapToJsonStrObjEncryption(map)
            ?.let { it1 -> mViewModel.onSelectedVideoMethod(it1) }

    }

    /** 视频播放器的设置 **/
    private fun initPlayer() {
        PlayerFactory.setPlayManager(Exo2PlayerManager::class.java)
        CacheFactory.setCacheManager(ProxyCacheManager::class.java)
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
        GSYVideoManager.instance().isNeedMute = false
    }


    override fun initData() {
        super.initData()
        binding.vpVideoListPlay.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageScrollStateChanged(position)
                loge("位置===" + position)
                pageChangeCallback(position)
            }
        })
    }

    private fun pageChangeCallback(position: Int) {
        positionIndex = position
        GSYVideoManager.releaseAllVideos()
        val itemData = mAdapter.getItemOrNull(position)
        if (itemData?.adView == null) {
            playPosition(position)
        }

        //查看当前的位置和总长度。如果不一样。直接不走后面 return
        val lastIndex = mAdapter.getDataLastIndex()
        loge("位置 position=" + position + "lastIndex=" + lastIndex + "isHasNext=" + isHasNext)
        if (position != lastIndex || !isHasNext) {
            return
        }

        //如果当前位置和长度一样。说明是最后一个
        //要么进行显示广告。在广告里加载更多数据。要么直接在这个地方加载更多
        val lastItemData = mAdapter.getItemOrNull(lastIndex)
        loge("位置 position=" + position + "lastItemData=" + lastItemData.toString())
        if (lastItemData?.adView != null) {
            loadMoreData()
            return
        }
        loadMoreData()
        //添加广告

//        loadAdInfo()
    }

    override fun onDestroy() {
        super.onDestroy()
        getShowPageHolder(positionIndex)?.destroyPlayer()
    }

    override fun onPause() {
        super.onPause()
        binding.vpVideoListPlay.postDelayed({
            getShowPageHolder(positionIndex)?.pausePlayer()
        }, 50)
        loge("测试=onPause")
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@GHVideoListFragment) {
                showToast(it)
            }
            againLoginMsg.observe(this@GHVideoListFragment) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onSelectedVideoData.observe(this@GHVideoListFragment) {
                onSuccessList(it.data.list, true)
            }
        }
    }

}

